package top.cluski.feieprint.service;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import top.cluski.feieprint.api.maiyatian.MaiyatianApi;
import top.cluski.feieprint.api.maiyatian.MaiyatianWebhookApi;
import top.cluski.feieprint.api.maiyatian.domain.dto.WebhookCreateOrderDTO;
import top.cluski.feieprint.api.maiyatian.domain.vo.WebhookCreateOrderVO;
import top.cluski.feieprint.api.maiyatian.entity.AccessTokenResponse;
import top.cluski.feieprint.api.teable.TeableApi;
import top.cluski.feieprint.api.teable.entity.RecordEntity;
import top.cluski.feieprint.api.youzan.YouzanApi;
import top.cluski.feieprint.api.youzan.entity.TradeOrderRespEntity;
import top.cluski.feieprint.domain.dto.MaiyationCreateOrderDTO;
import top.cluski.feieprint.entity.MaiyatianOrdersEntity;
import top.cluski.feieprint.entity.MaiyationTokenEntity;
import top.cluski.feieprint.mapper.MaiyatianOrdersMapper;
import top.cluski.feieprint.mapper.MaiyatianTokenMapper;

import java.time.LocalDateTime;
import java.util.HashMap;

@Slf4j
@Service
public class MaiyatianService {

    @Resource
    MaiyatianApi maiyatianApi;
    @Resource
    TeableApi teableApi;
    @Resource
    MaiyatianWebhookApi maiyatianWebhookApi;
    @Resource
    YouzanApi youzanApi;

    @Resource
    MaiyatianTokenMapper maiyatianTokenMapper;
    @Resource
    MaiyatianOrdersMapper maiyatianOrdersMapper;

    public void login(String code) {
        AccessTokenResponse resp = maiyatianApi.getAccessToken(code);

        MaiyationTokenEntity maiyationTokenEntity = new MaiyationTokenEntity();
        maiyationTokenEntity.setId(1);
        maiyationTokenEntity.setToken(resp.getToken());
        maiyationTokenEntity.setRefreshToken(resp.getRefreshToken());
        maiyationTokenEntity.setCreateTime(LocalDateTime.now());
        maiyatianTokenMapper.update(maiyationTokenEntity);

        log.info("resp={}", resp);
    }

    public void refreshToken() {
        MaiyationTokenEntity maiyationTokenEntity = maiyatianTokenMapper.selectOneById(1);

        AccessTokenResponse accessTokenResponse = maiyatianApi.refreshToken(maiyationTokenEntity.getToken(), maiyationTokenEntity.getRefreshToken());
        // update
        maiyationTokenEntity.setToken(accessTokenResponse.getToken());
        maiyationTokenEntity.setRefreshToken(accessTokenResponse.getRefreshToken());
        maiyationTokenEntity.setCreateTime(LocalDateTime.now());
        maiyatianTokenMapper.update(maiyationTokenEntity);
        log.info("resp={}", accessTokenResponse);
    }

    public void getOrderList() {
        MaiyationTokenEntity maiyationTokenEntity = maiyatianTokenMapper.selectOneById(1);
        System.out.println(maiyatianApi.getOrderList());
    }

    public void createOrder(MaiyationCreateOrderDTO maiyationCreateOrderDTO) {
        RecordEntity record = teableApi.getOneRecord(maiyationCreateOrderDTO.getRecordId());
        JSONObject fields = record.getFields();
        String peisongfangshi = fields.getString("配送方式");
        if (!"跑腿".equals(peisongfangshi) && !"闪送汽车".equals(peisongfangshi)) {
            return;
        }
        String phone = fields.getString("联系电话");
        String address = fields.getString("地址");
        if (address.split("\n").length > 1 && address.split("\n")[0].contains(":")) {
            address = address.split("\n")[1];
        }

        HashMap<String, Object> innerRemark = new HashMap<>();
        String youzanOrderId = fields.getString("有赞订单号");
        if (StrUtil.isNotEmpty(youzanOrderId)) {
            innerRemark.put("有赞订单号", youzanOrderId);
        }
        String type = fields.getString("款式");
        innerRemark.put("款式", type);

        String deliveryShop = fields.getString("配送店铺");

        TradeOrderRespEntity.FullOrderInfo orderDetail = youzanApi.getOrderDetail(youzanOrderId);
        String addressExtra = orderDetail.getAddress_info().getAddress_extra();
        JSONObject jsonObject = JSON.parseObject(addressExtra);
        Double lng = jsonObject.getDouble("lon");
        Double lat = jsonObject.getDouble("lat");

        WebhookCreateOrderDTO webhookCreateOrderDTO = WebhookCreateOrderDTO.create()
                .setUsername(phone).setMobileNo(phone)
                .setMapAddress(address)
                .setAddress(address)
                .setInnerRemark(innerRemark)
                .setDeliveryShop(deliveryShop)
                .setLng(lng)
                .setLat(lat);
        WebhookCreateOrderVO webhookCreateOrderVO = maiyatianWebhookApi.createOrder(webhookCreateOrderDTO);
        if (StrUtil.isNotEmpty(youzanOrderId)) {
            maiyatianOrdersMapper.insert(MaiyatianOrdersEntity.create()
                    .setMaiyatianOrderId(webhookCreateOrderVO.getId())
                    .setYouzanOrderId(youzanOrderId));
        }
    }
}
